#!/usr/sbin/rsct/perl5/bin/perl 
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 1999,2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 
# "@(#)92   1.15   src/rsct/registry/cli/bin/pwdsr.perl, srcli, rsct_rpyxh, rpyxht1f3 2/22/01 16:25:21"
######################################################################
#                                                                    #
# Module: pwdsr                                                      #
#                                                                    #
# Purpose:                                                           #
#   pwdsr - Displays the current working directory.                  #
#                                                                    #
# Syntax:                                                            #
#   pwdsr [-h][-TV]                                                  #
#                                                                    #
# Flags:                                                             #
#   -h   Help. Prints usage statement to standard out.               #
#   -T   Trace. Prints trace messages to standard error.             #
#   -V   Verbose. Prints verbose messages to standard error.         #
#                                                                    #
# Operands:                                                          #
#   None.                                                            #
#                                                                    #
# Description:                                                       #
#   pwdsr displays the current working directory according to the    #
#   value of the environment variable CT_SR_HOME. This variable is   #
#   used in establishing all registry sessions.                      #
#                                                                    #
#   The command first sets the working directory in the System       #
#   Registry using CT::SR::change_current_directory, (in the sub     #
#   init_session) then retrieves the value via                       #
#   CT::SR::get_current_directory.  This verifies that the Registry  #
#   does store the current directory value properly.                 #
#                                                                    #
# Exit Values:                                                       #
#   0  SR_CLI_SUCCESS        Command completed successfully.         #
#   1  SR_CLI_REGISTRY_ERROR Command terminated due to an underlying #
#                            System Registry error.                  #
#   2  SR_CLI_ERROR          Command terminated due to an underlying #
#                            error in the command script.            #
#   3  SR_CLI_BAD_OPERAND    Command terminated due to user          #
#                            specifying a bad operand.               #
#   4  SR_CLI_BAD_FLAG       Command terminated due to user          #
#                            specifying an invalid flag.             #
#   5  SR_CLI_USER_ERROR     Command terminated due to a user error. #
#                            For example specifying an undefined     #
#                            directory for CT_SR_HOME.               #
#                                                                    #
# Examples:                                                          #
#   pwdsr -h                                                         #
#   pwdsr -V                                                         #
#   pwdsr                                                            #
#                                                                    #
#--------------------------------------------------------------------#
#                                                                    #
# Inputs:                                                            #
#   user input from command line or file                             #
#                                                                    #
# Outputs:                                                           #
#   stdout - progress and/or Verbose messages                        #
#   stderr - error messages                                          #
#                                                                    #
# External Ref:                                                      #
#   Commands: $LSMSG                                                 #
#   Extensions:  CT::SR.pm CT::SRrc.pm                               #
#   Perl library routines: Getopts::Std                              #
#   CLI library routines:                                            #
#           SR_cli_utils - init_session error_exit                   #
#                          term_session printCEMsg                   #
#   Environment variables:                                           #
#           CT_SR_HOME                                               #
#                                                                    #
# Tab Settings:                                                      #
#   4 and tabs should be expanded to spaces before saving this file. #
#   in vi:  (:set ts=4  and   :%!expand -4)                          #
#                                                                    #
# Change Activity:                                                   #
#   000929 HGJ 38317: Initial delivery.                              #
#                                                                    #
######################################################################

#--------------------------------------------------------------------#
# General Program Flow/Logic:                                        #
#                                                                    #
# A: Parse command line - get table name and input file              #
# B: Initialise session with registry, including changing the        #
#    current directory if a relative path name is given (use value   #
#    given in CT_SR_HOME.)                                           #
# C: Call CT::SR::get_current_directory.                             #
# D: Display the current directory as returned in C:                 #
# E: Clean up session table and tree                                 #
#                                                                    #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# Included Libraries and Extensions                                  #
#--------------------------------------------------------------------#
use lib "/usr/sbin/rsct/pm";
use locale;
use Getopt::Std;
use Env qw(CT_SR_HOME);

use CT_cli_utils qw(printIMsg
                    printEMsg
);

use CT::SRrc;
use CT::SR;
use CT::SR qw (:sr_entry_t);
use SR_cli_utils qw(init_session 
                    term_session 
                    printCEMsg
                    $DEFAULT_GLOBAL_MOUNT_POINT
                    error_exit
);
use SR_cli_rc qw(:return_codes);


#--------------------------------------------------------------------#
# Global Variables                                                   #
#--------------------------------------------------------------------#
# Constants 
$TRUE       = 1;
$FALSE      = 0;

# Other Global Variables
$Verbose        = $FALSE;
$Trace          = $FALSE;

$PROGNAME       = "pwdsr";             # Program Name for messages
$MSGCAT         = "srcli.cat";         # msg catalogue for this cmd
$CTDIR          ="/usr/sbin/rsct";     # Cluster Bin directory path
$CTBINDIR       ="$CTDIR/bin";         # Cluster Bin directory path
$LSMSG          ="$CTBINDIR/ctdspmsg"; # display message rtn.
$ENV{'MSGMAPPATH'}="$CTDIR/msgmaps";   # Msg map path for $LSMSG 

%Cleanup = ();                         # Hash of items to cleanup
                                       # {Session} $session to term

#--------------------------------------------------------------------#
# Variables                                                          #
#--------------------------------------------------------------------#
# Variables to be used with extensions
my $Tree_handle    = "";                   # set in init_session

# Other Global Variables
my $rc             = 0;                    # assume good return code
my $Current_working_directory = "";
my $Set_work_dir   = $FALSE;
my $Mount_point    = $DEFAULT_GLOBAL_MOUNT_POINT;


#--------------------------------------------------------------------#
# Main Code                                                          #
#--------------------------------------------------------------------#

# TODO: Trace/Verbose messages in this routine that aren't using msg
# maps are trace statements. When trace facilities are available to
# the SR these will be changed. (feature 48401)


# Parse the command line, exit if there are errors
($rc) = parse_cmd_line();  
($rc == 0) || error_exit($rc); 

# If the environment variable CT_SR_HOME is set, then the working i
# directory must be set in the registry. 
if ($CT_SR_HOME) { $Set_work_dir = $TRUE; }

# Open a local tree and initialise a session with the registry library
($rc, $Tree_handle) = init_session($Set_work_dir);
($rc == 0) || error_exit($rc); 

# Add the tree handle to the cleanup hash
$Cleanup{Session} = $Tree_handle;

# Get the current working directory from the registry
$Trace && print STDERR "Calling CT::SR::get_current_directory\n";
$rc = CT::SR::get_current_directory($Tree_handle, 
                        $Current_working_directory);
$Trace && 
    print STDERR "CT::SR::get_current_directory return code: $rc\n";

if ($rc != 0) {
    printEMsg("EMsgpwdsrErrorGettingCurrentDirectory", $rc);
    printCEMsg("EMsgSRcliSRCommandFailure", 
                        "sr_get_current_directory", $rc);

    # Exit with the least non-zero return code
    error_exit($rc);
}

if ($CT_SR_HOME) {  
    $Trace && print STDERR "Calling sub validate_directory($Current_working_directory)\n";
    $rc = validate_directory($Current_working_directory, $Tree_handle);
    $Trace && print STDERR "validate_directory return code: $rc\n";
    ($rc == 0) || error_exit($rc);
}

# Only print out the value if it has been verified as valid
# Strip off the leading "/SR" as it is internal information
# TODO: This will have to be made NLS compliant, for sure!
if ($Set_work_dir) { $Current_working_directory =~ s/^\/SR//; }

# Print out the current working directory to verify that
# the registry server is receiving the data correctly when it's
# assigned.
print "$Current_working_directory\n";


# Clean up after program - close session tree.    
$rc = term_session($Tree_handle, $Mount_point);

exit $rc;

#--------------------------------------------------------------------#
# End Main Code                                                      #
#--------------------------------------------------------------------#


#--------------------------------------------------------------------#
# validate_directory:                                                #
#   Uses CT::SR::is_in_directory to verify that the current working  #
#   directory is valid. Verifies that the path is a directory        #
#   and not a table or unknown type.                                 #
#                                                                    #
# Parameters:                                                        #
#   $directory - the current working directory to be validated.      #
#                                                                    #
# Return values:                                                     #
#   $local_rc - local return code - assumed 0 to start.              #
#                                                                    #
# Global variables used:                                             #
#   None.                                                            #
#--------------------------------------------------------------------#
sub validate_directory 
{
my ($directory, $tree) = @_;

my ($temp_dir, $parent_dir, $entry);
my $type = 0;
my $storage = 0;
my $local_rc = 0;

# Strip off /SR for use in any possible messaging
# (value is internal to the CLI.) 
$temp_dir = $directory;
$temp_dir =~ s/^\/SR//; 

# Split off the right most entry in the current directory so
# there is a parent directory and entry to pass to SR:is_in_directory

$parent_dir = $directory;
$parent_dir =~ s/(.*)\/.*$/$1/;

$entry = $directory;
$entry =~ s/.*\/(.*)$/$1/;

$Trace && 
print STDERR "Calling CT::SR::is_in_directory($parent_dir, $entry)\n";

$local_rc = CT::SR::is_in_directory($tree, $parent_dir, $entry, 
                        $type, $storage);
$Trace && 
    print STDERR "CT::SR::is_in_directory return code: $local_rc\n";

$local_rc = error_check("sr_is_in_directory", $local_rc, $temp_dir, 
    $parent_dir, $entry);
($local_rc == 0) || return $local_rc; 

# Verify that the entry checked is not a table
# If it is an unknown type, is considered a severe Registry Error
if ($type == SR_TABLE){
    $Verbose && print STDERR "Entry type is $type\n";
    printEMsg("EMsgpwdsrCWDisTable", $temp_dir);
    $local_rc = SR_CLI_USER_ERROR;
}
elsif ($type == SR_UNKNOWN_ENTRY) {
    $Verbose && print STDERR "Entry type is $type\n";
    printEMsg("EMsgpwdsrCWDUnknown", $temp_dir);
    $local_rc = SR_CLI_REGISTRY_ERROR;
}

return $local_rc;
}   # end validate_directory


#--------------------------------------------------------------------#
# parse_cmd_line:                                                    #
#   Uses getopts() to grab flags on the command line.                #
#                                                                    #
# Return values:                                                     #
#   $local_rc - local return code - assumed 0 to start.              #
#                                                                    #
# Global variables modified:                                         #
#   $Trace             output   True (-T) turn Trace mode on.        #
#   $Verbose           output   True (-V) turn Verbose mode on.      #
#--------------------------------------------------------------------#
sub parse_cmd_line
{
my $local_rc = 0;;
my %opts = ();

if (getopts('hTV', \%opts) == 0) {       # Parse input flags
    printCEMsg("EMsgSRcliInvalidFlag");
    print_usage();
    return SR_CLI_BAD_FLAG;     
}     

if (defined $opts{h}) {          # Help flag - print usage and exit
    print_usage();
    exit 0;
}

if (defined $opts{V}) {          # Verbose - set global and continue
    $Verbose = $TRUE;
}

if (defined $opts{T}) {          # Trace - set global and continue
    $Trace = $TRUE;
}

if (@ARGV) {                     # Operands not allowed with this cmd.
    printEMsg("EMsgpwdsrInvalidUsage");
    print_usage();
    return SR_CLI_BAD_OPERAND;
}

return $local_rc;
}   # end parse_cmd_line


#--------------------------------------------------------------------#
# error_check:                                                       #
#   Checks the return code from the SR function.  If an error is     #
#   detected appropriate error messages will be displayed and        #
#   SR CLI return code set.                                          #
#                                                                    #
# Parameters:                                                        #
#   $sr_function  - Name of the SR function that was called and      #
#                   whose error code we are checking.                #
#   $sr_rc        - SR function return code.                         #
#   $temp_dir                                                        #
#   $parent_dir                                                      #
#   $entry                                                           #
#                                                                    #
# Return values:                                                     #
#   None.                                                            #
#                                                                    #
# Global References:                                                 #
#   None.                                                            #
#--------------------------------------------------------------------#
sub error_check
{   
my ($sr_function, $sr_rc, $temp_dir, $parent_dir, $entry) = @_;
my $rc = 0;

if ($sr_rc != 0) {
    if ($sr_rc == SR_NO_DIRECTORY) {
        printEMsg("EMsgpwdsrNoDirectory", $temp_dir);
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_NO_PERMISSION) {
        printEMsg("EMsgpwdsrNoPermission");
        $rc = SR_CLI_USER_ERROR;
    }
    elsif ($sr_rc == SR_NO_ENTRY) {
        $parent_dir =~ s/^\/SR/\//;
        printEMsg("EMsgpwdsrNoRightmostDir", $entry, $parent_dir);
        $rc = SR_CLI_USER_ERROR;
    }
    else {
        printEMsg("EMsgpwdsrErrorValidatingDir", $temp_dir);
        printCEMsg("EMsgSRcliSRCommandFailure", $sr_function, $sr_rc);
        $rc = SR_CLI_REGISTRY_ERROR;
    }
}

return ($rc);
}   # end error_check


#--------------------------------------------------------------------#
# print_usage : print the usage statement (syntax) to stdout.        #
#   See this command's prologue syntax section for current usage.    #
#--------------------------------------------------------------------#
sub print_usage
{
printIMsg("IMsgpwdsrUsage");
}   # end print_usage


#--------------------------------------------------------------------#
# End File                                                           #
#--------------------------------------------------------------------#
